package com.itheima.controller;

import com.itheima.common.R;
import com.itheima.dto.DeleteDTO;
import com.itheima.dto.ShoppingCartDTO;
import com.itheima.entity.ShoppingCart;
import com.itheima.service.ShoppingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.List;

/**购物车接口
 * @author msi
 */
@RequestMapping("/shoppingCart")
@RestController
public class ShoppingCartController {
    @Autowired
    private ShoppingService service;

    @GetMapping("/list")
    public R<List<ShoppingCart>> getList(HttpServletRequest request) {
        String userId = request.getHeader("Authornized");
        List<ShoppingCart> list = service.getList(userId);

        //因为前端网页一定要购物车返回列表里能遍历到0以上的元素数量，所以设置一个假的返回
        if (list==null){
            list=new ArrayList<>();
        }
        return R.success(list);
    }

    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCartDTO shoppingCartDTO, HttpServletRequest request) {
        String userId = request.getHeader("Authornized");
        ShoppingCart add = service.addDish(shoppingCartDTO, userId);
        return R.success(add);
    }

    @DeleteMapping("/clean")
    public R<String> clean(HttpServletRequest request) {
        String userId = request.getHeader("Authornized");
        service.clean(userId);
        return R.success("购物车已清空");
    }

    /**
     * 此接口接口文档返回值定义不清楚
     * 实际一定要返回一个有number属性的datagitst
     *
     * @param deleteDTO
     * @return 一个有number属性的data
     */
    @PostMapping("/sub")
    public R<ShoppingCart> delete(@RequestBody DeleteDTO deleteDTO,HttpServletRequest request) {
        String userId = request.getHeader("Authornized");
        Integer number = service.delete(deleteDTO,userId);

        ShoppingCart shoppingCart = new ShoppingCart();
        if (number != null) {
            shoppingCart.setNumber(number);
            return R.success(shoppingCart);
        }
        shoppingCart.setNumber(0);

        return R.success(shoppingCart);
    }

}
